<!-- 翻页模块 -->

<template>
  <div class="pagination">
    <el-button
      size="mini"
      icon="el-icon-arrow-left"
      @click="handlePrev"
      :disabled="current == 1"
    >上一页</el-button>
    <!-- pageData[0]等于1 -->
    <span v-for="i in pageData" class="page-item" :key="i">
      <el-button size="mini" type="text" v-if="current === i" :disabled="true">{{i}}</el-button>
      <el-button size="mini" type="text" v-else @click="() => handleClick(i)">{{i}}</el-button>
    </span>
    <el-input v-model="jumpPage" size="mini" style="width: 50px;"></el-input>
    <el-button size="mini" @click="handleJump" :disabled="jumpPage < 1 || jumpPage > total">跳转</el-button>

    <el-button
      size="mini" 
      @click="handleNext"
      :disabled="current == total"
    >
      下一页
      <i class="el-icon-arrow-right el-icon--right"></i>
    </el-button>
  </div>
</template>

<script>
export default {
 props: {
    total: { type: Number }, // 总页数
    length: { type: Number, default: 5 }, // 显示的页码数量
    defaultValue: { type: Number, default: 1 }, // 默认选中的页码
    onChange: { type: Function, default: () => {} } // 页码变化时的回调函数
  },

  data() {
    return {
      current: this.defaultValue, // 当前选中的页码
      jumpPage: '' // 跳转输入框中的值
    };
  },
  computed: {
    // 计算属性，计算展示的页码数组
    pageData: function () {
      const { current, total, length } = this;
      let start = Math.max(0, current - 2);
      const end = Math.min(total, start + length);
      if (end - start < length) {
        start = Math.max(0, end - length);
      }
      //创建一个包含从 1 到 total 的数组
      return Array.from({ length: total }, (_, i) => i + 1).slice(start, end);
      //映射函数 (_, i) => i + 1 用于将数组的每个元素的值设为其对应的索引 i + 1
    }
  },

  methods: {
    // 处理点击页码按钮
    handleClick(current) {
      this.current = current;
      this.onChange(this.current);
    },
    // 处理点击上一页按钮
    handlePrev() {
      this.current = Math.max(this.current - 1, 1);
      this.onChange(this.current);
    },
    // 处理点击下一页按钮
    handleNext() {
      this.current = Math.min(this.current + 1, this.total);
      this.onChange(this.current);
    },
    // 处理点击跳转按钮
    handleJump() {   
      const jumpPage = parseInt(this.jumpPage, 10);
      if (jumpPage >= 1 && jumpPage <= this.total) {
        this.current = jumpPage;
        this.onChange(this.current);
    }
  }
  }
}
</script>

<style scoped lang="less">
  .page-item {
    display: inline-block;
    margin: 0 5px;

    .is-disabled:hover {
      cursor: text !important;
    }
  }
</style>
